package com.ideal.frame.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ideal.frame.sys.entity.SysLog;
import com.ideal.frame.sys.entity.SysUser;
import com.ideal.frame.sys.service.SysLogService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;

/**
 * 日志拦截器
 */
@Component
@Slf4j
public class LogInterceptor extends HandlerInterceptorAdapter {
    private NamedThreadLocal<SysLog> logThreadLocal = new NamedThreadLocal<>("Log-Thread-Local");
    @Autowired
    private SysLogService logsService;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long beginTime = System.currentTimeMillis();
        //根据request初始化log对象
        SysLog logs = logsService.getLogByRequest(request);
        //设置开始时间
        logs.setBeginTime(new Timestamp(beginTime));
        //设置方法中文名
        HandlerMethod method = (HandlerMethod)handler;
        ApiOperation description = method.getMethod().getAnnotation(ApiOperation.class);
        if(description != null) {
            logs.setTitle(description.value());
        }
        //设置操作人
        SysUser sysUser = (SysUser) request.getAttribute("user");
        if (sysUser != null) {
            logs.setLoginName(sysUser.getUsername());
        }
        logThreadLocal.set(logs);
        log.info("============记录日志============{}",objectMapper.writeValueAsString(logs));
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        SysLog logs = logThreadLocal.get();
        //设置异常
        String exception = ex == null ? null : ex.toString();
        logs.setException(exception);
        //设置结束时间
        logs.setEndTime(new Timestamp(System.currentTimeMillis()));

        logsService.save(logs);
        super.afterCompletion(request, response, handler, ex);
    }
}
